package com.ouc.dataMange.controller;

import java.io.File;
import java.net.URLEncoder;
import java.util.List;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import com.ouc.common.config.OUCAjaxResult;
import com.ouc.common.utils.excel.ExcelUtils;
import com.ouc.common.utils.file.FileUtils;
import com.ouc.dataMange.domain.SysDataPort;
import com.ouc.dataMange.service.ISysDataSetService;
import com.ouc.dataMange.service.ISysMemoryDeviceService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ouc.common.annotation.Log;
import com.ouc.common.core.controller.BaseController;
import com.ouc.common.core.domain.AjaxResult;
import com.ouc.common.enums.BusinessType;
import com.ouc.dataMange.domain.SysDataShip;
import com.ouc.dataMange.service.ISysDataShipService;
import com.ouc.common.utils.poi.ExcelUtil;
import com.ouc.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * sys_data_shipController
 *
 * @author ouc
 * @date 2025-08-04
 */
@RestController
@RequestMapping("/dataMange/sysDataShip")
public class SysDataShipController extends BaseController {
  @Autowired
  private ISysDataShipService sysDataShipService;

  @Autowired
  private ISysMemoryDeviceService memoryDeviceService;

  @Autowired
  private ISysDataSetService dataSetService;

  /**
   * 查询sys_data_ship列表
   */
//    @PreAuthorize("@ss.hasPermi('dataMange:sys_data_ship:list')")
  @GetMapping("/list")
  public TableDataInfo list(SysDataShip sysDataShip) {
    startPage();
    List<SysDataShip> list = sysDataShipService.selectSysDataShipList(sysDataShip);
    for (SysDataShip dataShip : list) {
      dataShip.setRaoFileName(FileUtils.getName(dataShip.getShipRaoPath()));
    }
    return getDataTable(list);
  }

  /**
   * 导出sys_data_ship列表
   */
//    @PreAuthorize("@ss.hasPermi('dataMange:sys_data_ship:export')")
  @Log(title = "sys_data_ship", businessType = BusinessType.EXPORT)
  @RequestMapping("/export")
  public void export(HttpServletResponse response, SysDataShip sysDataShip) {
    List<SysDataShip> list = sysDataShipService.selectSysDataShipList(sysDataShip);
    ExcelUtil<SysDataShip> util = new ExcelUtil<SysDataShip>(SysDataShip.class);
    util.exportExcel(response, list, "舰船信息数据");
  }

  /**
   * 获取sys_data_ship详细信息
   */
  @PreAuthorize("@ss.hasPermi('dataMange:sys_data_ship:query')")
  @GetMapping(value = "/{id}")
  public AjaxResult getInfo(@PathVariable("id") Integer id) {
    return success(sysDataShipService.selectSysDataShipById(id));
  }

  /**
   * 新增sys_data_ship
   */
  @PreAuthorize("@ss.hasPermi('dataMange:sys_data_ship:add')")
  @Log(title = "sys_data_ship", businessType = BusinessType.INSERT)
  @PostMapping
  public AjaxResult add(@RequestBody SysDataShip sysDataShip) {
    return toAjax(sysDataShipService.insertSysDataShip(sysDataShip));
  }

  /**
   * 修改sys_data_ship
   */
  @PreAuthorize("@ss.hasPermi('dataMange:sys_data_ship:edit')")
  @Log(title = "sys_data_ship", businessType = BusinessType.UPDATE)
  @PutMapping
  public AjaxResult edit(@RequestBody SysDataShip sysDataShip) {
    return toAjax(sysDataShipService.updateSysDataShip(sysDataShip));
  }

  /**
   * 删除sys_data_ship
   */
  @PreAuthorize("@ss.hasPermi('dataMange:sys_data_ship:remove')")
  @Log(title = "sys_data_ship", businessType = BusinessType.DELETE)
  @DeleteMapping("/{ids}")
  public AjaxResult remove(@PathVariable Integer[] ids) {
    return toAjax(sysDataShipService.deleteSysDataShipByIds(ids));
  }

  /**
   * 导入（上传excel文件导入数据库）
   */
  @ResponseBody
  @RequestMapping("/uploadData")
  public OUCAjaxResult uploadData(MultipartFile file) {
    try {
      String fileDir = "E:\\mydatabase\\temp\\";
      File newFile = new File(fileDir);
      if (!newFile.exists()) {
        newFile.mkdirs();
      }
      String[] split = file.getOriginalFilename().split("/");
      String fileName = split[split.length - 1];
      file.transferTo(new File(fileDir, fileName));
      File excelFile = new File(fileDir + fileName);

      List<SysDataShip> shipList = ExcelUtils.readFile(excelFile, SysDataShip.class);
      for (SysDataShip dataShip : shipList) {
        sysDataShipService.insertSysDataShip(dataShip);
      }
      return OUCAjaxResult.ok("已插入dataShip数据=" + shipList.size());
    } catch (Exception e) {
      return OUCAjaxResult.error(e.toString());
    }
  }

  /**
   * 上传RAO文件
   */
  @ResponseBody
  @RequestMapping("/uploadRaoFile")
  public OUCAjaxResult uploadRaoFile(MultipartFile file,
                                     @RequestParam(value = "shipId") Integer shipId,
                                     @RequestParam(value = "userName", required = false, defaultValue = "admin") String userName,
                                     @RequestParam(value = "userId", required = false, defaultValue = "1") Integer userId,
                                     @RequestParam(value = "dataSetId", required = false, defaultValue = "8") Integer dataSetId,
                                     @RequestParam(value = "memoryId", required = false, defaultValue = "11") Integer memoryId) {
    try {
      String fileDir = memoryDeviceService.selectSysMemoryDeviceById(memoryId).getSysMemoryDevice()
          + dataSetService.selectSysDataSetById(dataSetId).getDataSetDevice() + File.separator + shipId + File.separator;
      File newFile = new File(fileDir);
      if (!newFile.exists()) {
        newFile.mkdirs();
      }
      String[] split = file.getOriginalFilename().split("/");
      String fileName = split[split.length - 1];
      file.transferTo(new File(fileDir, fileName));
      SysDataShip dataShip = new SysDataShip();
      dataShip.setId(shipId);
      dataShip.setShipRaoPath(File.separator + shipId + File.separator + fileName);
      sysDataShipService.updateSysDataShip(dataShip);
      return OUCAjaxResult.ok("已成功添加" + shipId + "号船的RAO文件，路径为" + fileDir + fileName);
    } catch (Exception e) {
      return OUCAjaxResult.error(e.toString());
    }
  }

  /**
   * 上传船舶装备文件
   */
  @ResponseBody
  @PostMapping("/uploadEquipFile")
  public OUCAjaxResult uploadEquipFile(MultipartFile file,
                                       @RequestParam(value = "shipId") Integer shipId,
                                       @RequestParam(value = "userName", required = false, defaultValue = "admin") String userName,
                                       @RequestParam(value = "userId", required = false, defaultValue = "1") Integer userId,
                                       @RequestParam(value = "dataSetId", required = false, defaultValue = "10") Integer dataSetId,
                                       @RequestParam(value = "memoryId", required = false, defaultValue = "13") Integer memoryId) {
    try {
      String fileDir = memoryDeviceService.selectSysMemoryDeviceById(memoryId).getSysMemoryDevice()
          + dataSetService.selectSysDataSetById(dataSetId).getDataSetDevice() + File.separator + shipId + File.separator;
      File newFile = new File(fileDir);
      if (!newFile.exists()) {
        newFile.mkdirs();
      }
      String[] split = file.getOriginalFilename().split("/");
      String fileName = split[split.length - 1];
      file.transferTo(new File(fileDir, fileName));
      SysDataShip dataShip = new SysDataShip();
      dataShip.setId(shipId);
      dataShip.setShipEquipPath(File.separator + shipId + File.separator + fileName);
      sysDataShipService.updateSysDataShip(dataShip);
      return OUCAjaxResult.ok("已成功添加" + shipId + "号船的装备文件，路径为" + fileDir + fileName);
    } catch (Exception e) {
      return OUCAjaxResult.error(e.toString());
    }
  }

  /**
   * 下载船舶装备信息文件
   */
  @ResponseBody
  @GetMapping("/downloadEquipFile")
  public OUCAjaxResult downloadEquipFile(HttpServletResponse response, Integer shipId,
                                         @RequestParam(value = "dataSetId", required = false, defaultValue = "10") Integer dataSetId,
                                         @RequestParam(value = "memoryId", required = false, defaultValue = "13") Integer memoryId) {
    try {
      SysDataShip dataShip = sysDataShipService.selectSysDataShipById(shipId);
      if (dataShip == null || dataShip.getShipEquipPath() == null) {
        return OUCAjaxResult.error("文件不存在");
      }
      String filePath = memoryDeviceService.selectSysMemoryDeviceById(memoryId).getSysMemoryDevice()
          + dataSetService.selectSysDataSetById(dataSetId).getDataSetDevice() + dataShip.getShipEquipPath();
      if (!new File(filePath).exists()) {
        return OUCAjaxResult.error("文件不存在，请重试");
      }
      File file = new File(filePath);
      response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));//文件下载
      ServletOutputStream outputStream = response.getOutputStream();
      outputStream.write(FileUtils.getFileByteArray(file));//把文件的字节数写出去
      outputStream.flush();//刷新一下
      outputStream.close();//一定要关闭文件流

      return OUCAjaxResult.ok("文件下载成功");
    } catch (Exception e) {
      return OUCAjaxResult.error(e);
    }
  }


}
